package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Article;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.User;
import com.itheima.service.Userservice;
import com.itheima.utils.Md5Util;
import com.itheima.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements Userservice {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User findByUserName(String username) {
        User u = userMapper.findByUserName(username);
        return u;
    }

    @Override
    public String findEmailByUserName(String username) {
        String UserEmail = userMapper.findEmailByUserName(username);
        return UserEmail;
    }

    @Override
    public void register(String username, String password,String email,String nickname) {
        String md5util = Md5Util.getMD5String(password);
        userMapper.add(username,md5util,email,nickname);
    }

    @Override
    public void update(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);

    }

    @Override
    public void updateAvatar(String avatarUrl) {
        Map<String,Object> map  = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        userMapper.updateAvatar(avatarUrl,id);
    }

    @Override
    public void updatePassword(String newPwd) {
        Map<String,Object> map  = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        String md5Util = Md5Util.getMD5String(newPwd);
        userMapper.updatePwd(md5Util,id);
    }
    @Override
    public void forgetPassword(String newPwd,String username) {
        Integer id = userMapper.findIdByUserName(username);
        String md5Util = Md5Util.getMD5String(newPwd);
        userMapper.updatePwd(md5Util,id);
    }

    @Override
    public PageBean<User> findAllUser(Integer pageNum, Integer pageSize, String nickname, String email) {
        PageBean<User> pb = new PageBean<>();

        PageHelper.startPage(pageNum,pageSize);

        List<User> la =  userMapper.findAllUser(nickname,email);

        Page<User> p = (Page<User>) la;

        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }

    @Override
    public void deleteUser(Integer id) {
        userMapper.deleteUser(id);
    }
}
